package com.developer.platform.domain.service.impl;

import static com.developer.platform.infrastructure.error.NoticeErrorType.ONLIENT_TIME_ERROR;

import cn.hutool.core.bean.BeanUtil;
import com.developer.platform.domain.NoticeAggregateRoot;
import com.developer.platform.domain.event.NoticeEvent;
import com.developer.platform.domain.event.NoticeEventPublisher;
import com.developer.platform.domain.repository.INoticeRepository;
import com.developer.platform.domain.service.INoticeService;
import com.veeker.core.exceptions.BusinessException;
import org.springframework.stereotype.Repository;

/**
 * @author ：qiaoliang
 * @date ：2020-11-10
 */
@Repository
public class NoticeServiceImpl implements INoticeService {

    private final INoticeRepository noticeRepository;
    private final NoticeEventPublisher noticeEventPublisher;

    public NoticeServiceImpl(INoticeRepository noticeRepository,
        NoticeEventPublisher noticeEventPublisher) {
        this.noticeRepository = noticeRepository;
        this.noticeEventPublisher = noticeEventPublisher;
    }

    @Override
    public void save(NoticeAggregateRoot noticeAggregateRoot) {
        noticeRepository.save(noticeAggregateRoot);
        this.sendMsg(noticeAggregateRoot);
    }

    @Override
    public void update(NoticeAggregateRoot noticeAggregateRoot) {
        BusinessException.isTrue((noticeAggregateRoot.getOnlineTime().getTime() - System.currentTimeMillis()) <= 0, ONLIENT_TIME_ERROR);
        noticeRepository.update(noticeAggregateRoot);
        this.sendMsg(noticeAggregateRoot);
    }

    @Override
    public void delete(long id) {
        noticeRepository.delete(id);
    }

    private void sendMsg(NoticeAggregateRoot noticeAggregateRoot){
        NoticeEvent noticeEvent = new NoticeEvent();
        BeanUtil.copyProperties(noticeAggregateRoot, noticeEvent);
        noticeEventPublisher.asyncPublish(noticeEvent);
    }

}
